package com.chia.multienty.workflow.service.impl;

import com.chia.multienty.core.parameter.workflow.FlowableUserAddParameter;
import com.chia.multienty.core.parameter.workflow.FlowableUserSearchParameter;
import com.chia.multienty.workflow.service.FlowableUserService;
import lombok.RequiredArgsConstructor;
import org.flowable.engine.IdentityService;
import org.flowable.idm.api.User;
import org.flowable.idm.api.UserQuery;
import org.flowable.idm.engine.impl.persistence.entity.UserEntity;
import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@RequiredArgsConstructor
public class FlowableUserServiceImpl implements FlowableUserService {

    private final IdentityService identityService;

    @Override
    public void add(FlowableUserAddParameter parameter) {
        UserEntity user = new UserEntityImpl();
        user.setId(parameter.getId());
        user.setDisplayName(parameter.getDisplayName());
        user.setPassword(parameter.getPassword());
        user.setFirstName(parameter.getFirstName());
        user.setLastName(parameter.getLastName());
        user.setEmail(parameter.getEmail());
        user.setRevision(0);
        user.setTenantId(parameter.getTenantId());
        identityService.saveUser(user);
    }

    @Override
    public void delete(String id) {
        identityService.deleteUser(id);
    }

    @Override
    public List<User> list(FlowableUserSearchParameter parameter) {
        UserQuery userQuery = identityService.createUserQuery();
        if(parameter.getKeywords() != null) {
            userQuery = userQuery.userDisplayNameLike(parameter.getKeywords());
        }
        List<User> list = userQuery.orderByUserId().desc().listPage(parameter.getCurrentPage(), parameter.getPageSize());
        return list;
    }

}
